package com.core.system.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.Enums.ResponseEnum;
import com.common.exception.CourseException;
import com.common.util.CopyUtil;
import com.core.system.domain.Role;
import com.core.system.dto.RoleDto;
import com.core.system.mapper.RoleMapper;
import com.core.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RoleServiceImp extends ServiceImpl<RoleMapper, Role> implements RoleService{

   @Autowired
   private RoleMapper  roleMapper;
  
   @Override
    public ResponseEntity list(Page pageDto,  Role role) {
        IPage<Role> page = roleMapper.selectPage(new Page<>(pageDto.getCurrent(), pageDto.getSize()),
                new LambdaQueryWrapper<Role>(role));
        pageDto.setTotal(page.getTotal());
        List<RoleDto> roleDtoList = CopyUtil.copyList(page.getRecords(), RoleDto.class);
        pageDto.setRecords(roleDtoList);
        return ResponseEntity.ok(pageDto);
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    @Override
    public ResponseEntity save( RoleDto roleDto) {
        Role role = CopyUtil.copy(roleDto, Role.class);
        if (StringUtils.isEmpty(roleDto.getId())) {
            return this.insert(role);
        } else {
            return this.update(role);
        }

    }

    /**
     * 更新
     */
    private ResponseEntity update(Role role) {
        int i = roleMapper.updateById(role);
        if (i <= 0) {
            throw new CourseException(ResponseEnum.UPDATE_ERROR);
        }
        return ResponseEntity.ok(ResponseEnum.UPD_SUCCESS.getDesc());
    }

    /**
     * 新增
     */
    private ResponseEntity insert(Role role) {
        int i = roleMapper.insert(role);
        if (i <= 0) {
            throw new CourseException(ResponseEnum.ADD_ERROR);
        }
        return ResponseEntity.ok(ResponseEnum.ADD_SUCCESS.getDesc());
    }


    /**
     * 删除
     */
    @Override
    public ResponseEntity delAll(List<String> ids) {
        int i = roleMapper.deleteBatchIds(ids);
        if (i <= 0) {
            throw new CourseException(ResponseEnum.DELETE_ERROR);
        }
        return ResponseEntity.ok(ResponseEnum.DEL_SUCCESS.getDesc());
    }


}